package com.vecspace.web.servlet.model;

import com.vecspace.exception.HException;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class UrlInfo {
    private String resType;
    private String beanName;
    private String pathName;

    public UrlInfo(HttpServletRequest request){
        String uri = request.getRequestURI();
        while(uri.contains("//"))uri = uri.replace("//", "/");
        String servletPath = request.getServletPath();
        if(!servletPath.endsWith("/")) {
            servletPath = servletPath + "/";
        }
        String requestUrl = StringUtils.substringAfter(uri, servletPath);
        requestUrl = StringUtils.substringBefore(requestUrl, ";");
        requestUrl = StringUtils.substringBefore(requestUrl, "#");
        if(requestUrl.startsWith("/")) {
            requestUrl = requestUrl.substring(1);
        }

        //uriSections 三段式 /base/bean/method
        String[] uriSections = requestUrl.split("/");

        if(uriSections.length == 2 && "view".equals(uriSections[0])) { //只有访问页面时，才自动补充index页面地址
            uriSections = new String[] {uriSections[0], uriSections[1], "index"};
        }

        if(uriSections.length < 2) {
            throw new HException("3003", "URL格式错误:"+uri+",正确的格式应该是 base[view]/handler/method");
        }

        if(uriSections.length == 3) {
            resType = uriSections[0];
            beanName = uriSections[1];
            pathName = uriSections[2];
        }else {
            throw new HException("3003", "URL格式错误:"+uri+",正确的格式应该是 [saas]/base[view]/handler/method");
        }
    }
    public UrlInfo(String resType, String beanName, String pathName) {
        this.resType = resType;
        this.beanName = beanName;
        this.pathName = pathName;
    }
    /**请求资源的类型 base | file | xls | img | view*/
    public String getResType() {
        return resType;
    }

    /**请求资源的类型 base | file | xls | img | view */
    public void setResType(String requestType) {
        this.resType = requestType;
    }

    public String getBeanName() {
        return beanName;
    }

    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    public String getPathName() {
        return pathName;
    }

    public void setPathName(String pathName) {
        this.pathName = pathName;
    }
}
